import { login,logout } from '@/api/user'
import storageUtils from '@/util/index'

const user = {
    state: {
        username: '',
        token: '',
        nickname: '',
    },
    mutations: {
        /*
        将username,nickname,token保存到vuex中
        */
        SAVE_USERNAME(state, username) {
            state.username = username;
        },
        SAVE_NICKNAME(state, nickname) {
            state.nickname = nickname;
        },
        SAVE_TOKEN(state, token) {
            state.token = token;
        },

    },
    getters: {
        /**
         * 判断是否登录
         * @param {*} state 
         * @returns 
         */
        isLogin(state) {
            return !!state.token;
        }
    },
    actions: {
        /**
         * 登录
         * @param {*} param0 
         * @param {用户名，密码} user 
         * @returns 
         */
        LOGIN({ commit }, user1) {
            return new Promise(function (resolve, reject) {
                login(user1).then(res => {
                    //将username,nickname,token保存到vuex中
 
                    commit("SAVE_USERNAME", res.data.data.user.username);
                    commit("SAVE_NICKNAME", res.data.data.user.nickname);
                    commit("SAVE_TOKEN", res.data.data.token);
                    //再保存到sessionStorage中
                    storageUtils.saveSessionObject("loginUser", res.data.data);
                    resolve(res);
                }).catch(err => {
                    reject(err)
                })
            })
        },
        /**
         * 退出
         * 移除vuex和session中的数据
         * @param {*} param0 
         * @returns 
         */
        LOGOUT({ commit }) {
            return new Promise((resolve, reject) => {
                logout().then(res => {
                    commit("SAVE_USERNAME", '');
                    commit("SAVE_NICKNAME", '');
                    commit("SAVE_TOKEN", '');
                    storageUtils.removeData('loginUser');
                }).catch(err => {
                    reject(err)
                })
            })

        },
        /**
         * 恢复vuex
         * @param {*}
         */
        RESTORE_VUEX({commit}) {
        
            let loginUser = storageUtils.getSessionObject('loginUser');
            if (loginUser) {
                commit("SAVE_TOKEN", loginUser.token);   
                commit("SAVE_USERNAME", loginUser.user.username);
                commit("SAVE_NICKNAME", loginUser.user.nickname);
                      
            }
        },
       

    }
}

export default user;